package com.ruoyi.repay.service.impl;



import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.repay.config.AlipayConfig;
import com.ruoyi.repay.domain.AlipayBean;
import com.ruoyi.repay.domain.RepaymentDetails;
import com.ruoyi.repay.domain.RepaymentPlan;
import com.ruoyi.repay.mapper.RepaymentDetailsMapper;
import com.ruoyi.repay.mapper.RepaymentPlanMapper;
import com.ruoyi.repay.service.AlipayService;
import com.ruoyi.repay.service.RepayService;
import com.ruoyi.repay.utils.ApipayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class AlipayServiceImpl implements AlipayService {
    @Autowired
    RepaymentPlanMapper repaymentPlanMapper;
    @Autowired
    RepaymentDetailsMapper repaymentDetailsMapper;
    @Override
    public AjaxResult alipayPay(AlipayBean alipayBean)throws Exception {
        String alipay = ApipayUtils.pagepay(alipayBean);
        return AjaxResult.success(alipay);
    }

    @Override
    public String queryOrder(String out_trade_no) throws Exception {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();

        //请二选一设置
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\"}");

        //请求
        String result = alipayClient.execute(alipayRequest).getTradeStatus();

        //输出
        System.out.println(result);
        if (result.equals("TRADE_SUCCESS")) {
            // 交易成功

            repaymentDetailsMapper.update(out_trade_no,0);
            RepaymentDetails repaymentDetails = repaymentDetailsMapper.select(out_trade_no);
            repaymentDetails.setRepaymentDate(LocalDateTime.now());
            repaymentDetailsMapper.updates(repaymentDetails);


        } else {
            // 交易失败
            repaymentDetailsMapper.update(out_trade_no,1);
        }

        return result;
    }
}
